# GUI生成自deepseek
import os
import threading
import tkinter as tk
from tkinter import ttk, scrolledtext, Menu, messagebox

from src.core.qhd import Qhd


class QhdGUI:
    def __init__(self, master):
        """初始化GUI界面"""
        self.master = master
        master.title("智障0.3抢活动程序")
        
        # 全局样式变量
        self.font_family = '微软雅黑'  # 'Microsoft YaHei'
        self.font_size = 10
        self.button_fg = 'black'
        self.qhd = Qhd(self._append_output)
        # 窗口设置
        self._setup_window()
        # 样式配置
        self._configure_styles()
        # 创建控件
        self._create_widgets()
        # 检查并加载密码文件
        self._check_password_file()
        
    def _check_password_file(self):
        """检查并加载密码文件"""
        self.password_file = "passwd.txt"
        if os.path.exists(self.password_file):
            try:
                with open(self.password_file, "r", encoding="utf-8") as f:
                    lines = f.readlines()
                    if len(lines) >= 2:
                        uid = lines[0].strip()
                        passwd = lines[1].strip()
                        self.entry_uid.insert(0, uid)
                        self.entry_passwd.insert(0, passwd)
                        # 询问用户是否自动登录
                        if messagebox.askyesno("自动登录", "检测到保存的账号密码，是否自动登录？"):
                            self._login()
            except Exception as e:
                self._append_output(f"[错误] 读取密码文件失败: {str(e)}", 'error')
    
    def _save_password_to_file(self, uid, passwd):
        """保存账号密码到文件"""
        try:
            with open(self.password_file, "w", encoding="utf-8") as f:
                f.write(f"{uid}\n{passwd}\n")
            self._append_output("[信息] 账号密码已保存到本地文件", 'info')
        except Exception as e:
            self._append_output(f"[错误] 保存密码文件失败: {str(e)}", 'error')

    def _setup_window(self):
        """窗口位置和属性设置"""
        self.master.attributes('-topmost', True)
        window_width = 500
        window_height = 400
        screen_width = self.master.winfo_screenwidth()
        screen_height = self.master.winfo_screenheight()
        x = (screen_width - window_width) // 2
        y = (screen_height - window_height) // 2
        self.master.geometry(f"{window_width}x{window_height}+{x}+{y}")
        self.master.configure(bg='#f0f0f0')
        
    def _configure_styles(self):
        """配置ttk样式"""
        style = ttk.Style()
        base_font = (self.font_family, self.font_size)
        bold_font = (self.font_family, self.font_size, 'bold')
        
        style.configure('TLabel', font=base_font, foreground='#333333')
        style.configure('TEntry', font=base_font, padding=5)
        style.configure('TButton', 
                      font=base_font,
                      padding=6,
                      relief='flat',
                      foreground=self.button_fg)
        
        style.map('TButton',
                foreground=[],
                background=[('pressed', '#3a7ff6'), ('active', '#3a7ff6')])
        
        # 自定义按钮样式
        style.configure('Accent.TButton',
                     foreground=self.button_fg,
                     background='#3a7ff6',
                     font=bold_font,
                     padding=6)
        
        style.configure('Stop.TButton',
                     foreground=self.button_fg,
                     background='#ff4d4f',
                     font=bold_font,
                     padding=6)
        
        style.map('Accent.TButton', foreground=[], background=[])
        style.map('Stop.TButton', foreground=[], background=[])
        
    def _create_widgets(self):
        """创建所有界面组件"""
        base_font = (self.font_family, self.font_size)
        
        main_frame = ttk.Frame(self.master, padding="10")
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        # 学号输入区
        ttk.Label(main_frame, text="学号:").grid(row=0, column=0, padx=5, pady=5, sticky='w')
        self.entry_uid = ttk.Entry(main_frame)
        self.entry_uid.grid(row=0, column=1, padx=5, pady=5, sticky='ew')
        
        # 密码输入区
        ttk.Label(main_frame, text="密码:").grid(row=1, column=0, padx=5, pady=5, sticky='w')
        self.entry_passwd = ttk.Entry(main_frame, show="*")
        self.entry_passwd.grid(row=1, column=1, padx=5, pady=5, sticky='ew')
        
        # 活动id输入区（初始不显示）
        self.entry_wid_label = ttk.Label(main_frame, text="活动id:")
        self.entry_wid = ttk.Entry(main_frame)
        
        # 按钮框架
        button_frame = ttk.Frame(main_frame)
        button_frame.grid(row=2, column=0, columnspan=2, pady=10, sticky='ew')
        
        # 登录按钮
        self.btn_login = ttk.Button(button_frame, text="登录", command=self._login, style='Accent.TButton')
        self.btn_login.pack(fill=tk.X, expand=True)
        
        # 执行按钮（初始不显示）
        self.btn_execute = ttk.Button(button_frame, text="执行", command=self._execute, style='Accent.TButton')
        
        # 停止按钮（初始不显示）
        self.btn_stop = ttk.Button(button_frame, text="停止", command=self._stop, style='Stop.TButton')
        
        # 输出区
        output_frame = ttk.LabelFrame(main_frame, text="操作日志", padding=5)
        output_frame.grid(row=3, column=0, columnspan=2, sticky='nsew', pady=(10,0))
        
        main_frame.columnconfigure(1, weight=1)
        main_frame.rowconfigure(3, weight=1)
        
        # 输出文本框（禁止编辑但允许复制）
        self.output_text = scrolledtext.ScrolledText(
            output_frame,
            width=40,
            height=10,
            wrap=tk.WORD,
            font=base_font,
            bg='white',
            fg='#333333',
            insertbackground='#333333',
            selectbackground='#3a7ff6',
            selectforeground='white',
            state='disabled'  # 初始禁用状态
        )
        self.output_text.pack(fill=tk.BOTH, expand=True)
        
        # 配置右键菜单
        self._setup_right_click_menu()
        
    def _setup_right_click_menu(self):
        """配置右键菜单（仅复制功能）"""
        self.context_menu = Menu(self.output_text, tearoff=0)
        self.context_menu.add_command(label="复制", command=self._copy_text)
        
        def show_menu(event):
            if self.output_text.tag_ranges(tk.SEL):
                self.context_menu.post(event.x_root, event.y_root)
        
        self.output_text.bind("<Button-3>", show_menu)
        
    def _copy_text(self):
        """复制选中文本到剪贴板"""
        try:
            selected = self.output_text.get(tk.SEL_FIRST, tk.SEL_LAST)
            self.master.clipboard_clear()
            self.master.clipboard_append(selected)
        except tk.TclError:
            pass  # 没有选中文本时不操作
        
    def _login(self):
        """登录按钮回调函数"""
        uid = self.entry_uid.get()
        passwd = self.entry_passwd.get()
        
        if not uid or not passwd:
            self._append_output("[错误] 学号和密码不能为空！", 'error')
            return
        
        # 锁定输入框
        self.entry_uid.config(state=tk.DISABLED)
        self.entry_passwd.config(state=tk.DISABLED)
        self.btn_login.config(state=tk.DISABLED)
        
        def login():
            # 开始登陆
            if self.qhd.login(username=uid, password=passwd):
                # 保存账号密码到文件
                self._save_password_to_file(uid, passwd)
                # 隐藏登录按钮，显示执行按钮
                self.btn_login.pack_forget()
                self.btn_execute.pack(fill=tk.X, expand=True)
                # 隐藏密码输入框，显示活动id输入框
                self.entry_passwd.grid_forget()
                self.entry_wid_label.grid(row=1, column=0, padx=5, pady=5, sticky='w')
                self.entry_wid.grid(row=1, column=1, padx=5, pady=5, sticky='ew')
            else:
                self.entry_uid.config(state=tk.NORMAL)
                self.entry_passwd.config(state=tk.NORMAL)
                self.btn_login.config(state=tk.NORMAL)
        threading.Thread(
            target=login,
            daemon=True
        ).start()
        
    def _execute(self):
        """执行按钮回调函数"""
        # 获取wid，锁定活动id输入框
        wid = self.entry_wid.get()
        if not wid:
            self._append_output("[错误] 活动id不能为空！", 'error')
            return
        self.entry_wid.config(state=tk.DISABLED)
        
        # 隐藏执行按钮，显示停止按钮
        self.btn_execute.pack_forget()
        self.btn_stop.pack(fill=tk.X, expand=True)
        
        # 启动线程执行任务
        self.qhd.start_grab(wid, self._stop)
        
    def _stop(self):
        """停止按钮回调函数"""
        self.qhd.stop_grab()
        
        # 隐藏停止按钮，显示执行按钮
        self.btn_stop.pack_forget()
        self.btn_execute.pack(fill=tk.X, expand=True)
        # 启用活动id输入框
        self.entry_wid.config(state=tk.NORMAL)
        
        
    def _append_output(self, message, msg_type='normal'):
        """向输出框追加内容"""
        colors = {
            'normal': '#333333',
            'error': '#ff4d4f',
            'info': '#3a7ff6',
            'warning': '#faad14',
            'success': '#00AA00'
        }
        color = colors.get(msg_type, '#333333')
        
        # 临时启用编辑
        self.output_text.config(state='normal')
        self.output_text.insert(tk.END, message + "\n", msg_type)
        self.output_text.tag_config(msg_type, foreground=color)
        self.output_text.see(tk.END)
        # 重新禁用编辑
        self.output_text.config(state='disabled')
        self.output_text.update()
        print(message)

if __name__ == "__main__":
    root = tk.Tk()
    app = QhdGUI(root)
    root.mainloop()